﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace Luxury_car_sales_system
{
    class DBHelper
    {
        //连接字符串对象创建
        private static string sqlStr = "Data Source=LAPTOP-QH86SV1N\\miku;Initial Catalog=Cars;Integrated Security=True";
        public static SqlConnection conn = null;
        //数据库缓存数据
        public static DataSet dataSet = new DataSet();
        //数据库连接判断
        private static void sqlconn()
        {
            conn = new SqlConnection(sqlStr);
            if (conn.State == ConnectionState.Closed)
            {
                conn = new SqlConnection(sqlStr);
                conn.Open();
            }
            if (conn.State == ConnectionState.Broken)
            {
                conn.Close();
                conn.Open();
            }
        }
        //单向操作
        public static bool ExcuteNonQuery(string sql)
        {
            sqlconn();
            SqlCommand cmd = new SqlCommand(sql, conn);
            int result = cmd.ExecuteNonQuery();
            conn.Close();
            return result > 0;
        }
        //dataTable表获取
        public static DataTable getDataTable(string sql)
        {
            sqlconn();
            DataTable table = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
            sda.Fill(table);
            conn.Close();
            conn.Dispose();
            return table;
        }
        //存入缓存
        public static void getDataSet(string sql)
        {
            sqlconn();
            DataTable table = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
            sda.Fill(dataSet);
            conn.Close();
            conn.Dispose();
        }
        //datareader查询
        public static SqlDataReader GetDataReader(string sql)
        {
            sqlconn();
            SqlCommand cmd = new SqlCommand(sql, conn);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        //执行聚合函数
        public static object ExcuteScalar(string sql)
        {
            sqlconn();
            SqlCommand cmd = new SqlCommand(sql, conn);
            object result = cmd.ExecuteScalar();
            conn.Close();
            return result;
        }
    }
}
